package com.hzzc.core.service;

import com.hzzc.core.dao.SSOUserRoleMapper;
import com.hzzc.core.model.SSORole;
import com.hzzc.core.model.SSOUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * 用户与资源的关系
 */
@Service
public class UserRoleService {

    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;

    /**
     * 用户角色
     */
    @Autowired
    private SSOUserRoleMapper ssoUserRoleMapper;

    /**
     * 获取用户对于单个应用的资源列表
     *
     * @param userId
     * @param appId
     * @return
     */
    public List<SSORole> userRoleInThisApp(long userId, Long appId) {
        Example userRole = new Example(SSOUserRole.class);
        userRole.createCriteria().andEqualTo("applicationId", appId).andEqualTo("userId", userId);
        List<SSOUserRole> ssoUserRoles = ssoUserRoleMapper.selectByExample(userRole);
        Set<Long> roleIds = ssoUserRoles.stream().map(SSOUserRole::getRoleId).collect(Collectors.toSet());
        if (roleIds == null || roleIds.size() == 0) {
            return Collections.emptyList();
        }
        return roleService.selectByIds(roleIds);
    }

    /**
     * 更新用户的角色
     *
     * @param appId
     * @param userId
     * @param roleIds
     */
    public void updateUserRole(long appId, long userId, Set<Long> roleIds) {
        Example cleanUserRole = new Example(SSOUserRole.class);
        cleanUserRole.createCriteria().andEqualTo("userId", userId).andEqualTo("applicationId", appId);
        ssoUserRoleMapper.deleteByExample(cleanUserRole);
        List<SSOUserRole> ssoUserRoles = new ArrayList<>();
        for (Long roleId : roleIds) {
            ssoUserRoles.add(new SSOUserRole().setApplicationId(appId).setUserId(userId).setRoleId(roleId));
        }
        ssoUserRoleMapper.insertList(ssoUserRoles);
    }
}
